<?php
/**
 * Created by PhpStorm.
 * User: deng
 * Date: 2017/3/8
 * Time: 16:24
 */
class UserSettingModel {

    const UserSettingPreKey = 'UST/';

    const UserSettingCachePreKey = 'user:set:';

    private $diaryListCacheModel;

    static public $G = [];

    function __construct(){
        $this->diaryListCacheModel  =   new DiaryListCacheModel();
    }

    function saveSetting($uid, $set){
        $info = $this->getSettingInfo($uid);
        if ($info){
            //已经存在用户设置
            if ( isset($set['uid']) )  unset($set['uid']);
            return $this->update($uid, $set);
        }
        if (empty($set['uid'])) $set['uid'] = $uid;
        $set['created_at'] = AC::SERVER_TIME;
        $set['updated_at'] = AC::SERVER_TIME;
        return $this->insert($uid, $set);
    }

    function insert($uid, $info){
        $key = self::UserSettingPreKey. $uid;
        $result = Storage::addData($key, $info);
        return $result;
    }

    function update($uid, $set){
        $key = self::UserSettingPreKey. $uid;
        $setInfo = [];
        isset($set['diary_top']) && $setInfo['diary_top'] = $set['diary_top'];
        isset($set['extra'])    && $setInfo['extra']    = $set['extra'];
        isset($set['string3']) && $setInfo['string3'] = $set['string3'];
        if (empty($setInfo))
            return false;
        $setInfo['updated_at'] = AC::SERVER_TIME;
        $where = [ 'uid' => $uid ];
        $result = Storage::setConditionData($key, $setInfo, $where);
        $this->removeCache($uid);
        return $result;
    }

    function getSettingInfo($uid, $cached = true){
        $ckey = self::UserSettingCachePreKey. $uid;
        if (isset(self::$G[$ckey]))
            return self::$G[$ckey];
        $cache = $this->diaryListCacheModel->getStringByKey($ckey);
        if ($cache){
            $cache = json_decode($cache, true);
            self::$G[$ckey] = $cache;
            return $cache;
        }
        $key = self::UserSettingPreKey. $uid;
        $where = [ 'uid' => $uid ];
        $result = Storage::getConditionData($key, $where);
        if ($result){
            $this->diaryListCacheModel->addStringByKey($ckey, json_encode($result));
        }
        self::$G[$ckey] = $result;
        return $result;
    }

    function getDiaryTopFromSetting($setting){
        return $setting['diary_top'];
    }

    function removeCache($uid){
        $key = self::UserSettingCachePreKey. $uid;
        $this->diaryListCacheModel->removeStringByKey($key);
        unset(self::$G[$key]);
    }

}